package config

import (
	"fmt"
	"time"

	"github.com/BurntSushi/toml"
)

// DBConfig 数据库配置结构体
type DBConfig struct {
	Host            string        `toml:"host"`
	Port            string        `toml:"port"`
	User            string        `toml:"user"`
	Password        string        `toml:"password"`
	DBName          string        `toml:"dbname"`
	MaxIdleConns    int           `toml:"max_idle_conns"`
	MaxOpenConns    int           `toml:"max_open_conns"`
	ConnMaxLifetime time.Duration `toml:"conn_max_lifetime"`
	ConnMaxIdleTime time.Duration `toml:"conn_max_idle_time"`
	LogLevel        string        `toml:"log_level"`
}

type JWTConfig struct {
	Secret string `toml:"secret"`
	Expire int    `toml:"expire"`
}

type ServerConfig struct {
	Port int `toml:"port"`
}

// Config 全局配置结构体
type Config struct {
	Database DBConfig     `toml:"database"`
	JWT      JWTConfig    `toml:"jwt"`
	Server   ServerConfig `toml:"server"`
}

var SysConfig Config

// LoadConfig 从文件加载配置
func LoadConfig(path string) (*Config, error) {
	var config Config
	if _, err := toml.DecodeFile(path, &config); err != nil {
		return nil, fmt.Errorf("failed to load config: %v", err)
	}

	// 设置默认值
	if config.Database.MaxIdleConns == 0 {
		config.Database.MaxIdleConns = 10
	}
	if config.Database.MaxOpenConns == 0 {
		config.Database.MaxOpenConns = 100
	}
	if config.Database.ConnMaxLifetime == 0 {
		config.Database.ConnMaxLifetime = time.Hour
	}
	if config.Database.ConnMaxIdleTime == 0 {
		config.Database.ConnMaxIdleTime = 30 * time.Minute
	}
	if config.Database.LogLevel == "" {
		config.Database.LogLevel = "info"
	}
	SysConfig = config // 将配置信息绑定到结构体上
	return &config, nil
}
